package com.example.add8_17.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements BaseView {
    public P mPresenter;
    private Unbinder unbinder;
    private boolean mlsVisibleToUser;
    private boolean mlsViewCreated;
    private boolean mDataLoaded;
    private View mView;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView==null){
            mView = inflater.inflate(getLayout(), null);
            unbinder= ButterKnife.bind(this,mView);
            mPresenter=initPresenter();
            if (mPresenter!=null){
                mPresenter.bindView(this);
            }
            initView(mView);
            mlsViewCreated=true;
            laxyLoad();
            initListener();
        }
        return mView;
    }

    private void laxyLoad() {
        if (mlsViewCreated&&mlsVisibleToUser&&!mDataLoaded){
            mDataLoaded=true;
            initData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.mlsVisibleToUser=isVisibleToUser;
        laxyLoad();
    }

    protected abstract void initListener();

    protected abstract void initData();

    protected abstract P initPresenter();

    protected abstract void initView(View mView);

    protected abstract int getLayout();

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder=null;
        if (mPresenter!=null){
            mPresenter.dsetroy();
            mPresenter=null;
        }
    }
}
